//
//  HCConsoleLogFormatter.m
//  HCLog
//
//  Created by 韩昌 on 2017/7/11.
//  Copyright © 2017年 Han Chang. All rights reserved.
//

#import "HCConsoleLogFormatter.h"

@implementation HCConsoleLogFormatter

- (NSString *)formatLogMessage:(HCLogMessage *)logMessage
{
    if (!logMessage->_message) {
        return nil;
    }
    
    // Calculate date.
    NSTimeInterval seconds = [logMessage->_date timeIntervalSince1970];
    int milliseconds = (int)((seconds - floor(seconds)) * 1000);
    time_t time = (time_t)seconds;
    struct tm tm;
    localtime_r(&time, &tm);
    
    char date[24];
    bzero(date, sizeof(date));
    // yyyy-MM-dd HH:mm:ss.SSS
    snprintf(date, 24, "%04d-%02d-%02d %02d:%02d:%02d.%03d",
             tm.tm_year + 1900,
             tm.tm_mon + 1,
             tm.tm_mday,
             tm.tm_hour,
             tm.tm_min,
             tm.tm_sec,
             milliseconds);
    
    NSString *pid = logMessage->_processID;
    NSString *tid = logMessage->_threadID;
    
    if (logMessage->_tag.length > 0) {
        return [NSString stringWithFormat:@"%s [%@:%@] [%@] %@", date, pid, tid, logMessage->_tag, logMessage->_message];
    } else {
        return [NSString stringWithFormat:@"%s [%@:%@] %@", date, pid, tid, logMessage->_message];
    }
}

@end
